package server;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


import client.IClient;
import exception.NameTakenException;
import exception.UserNotConnectedException;

public class Server extends UnicastRemoteObject implements IServer {

	private static final long serialVersionUID = 1L;
	private HashMap<String, IClient> listIClients;
	
	public Server() throws RemoteException {
		super(0, new RMISSLClientSocketFactory(), new RMISSLServerSocketFactory());
		listIClients = new HashMap<String, IClient>();
	}

	@Override
	public synchronized void logOn(IClient client, String username)
			throws RemoteException, NameTakenException {
		if(listIClients.containsKey(username)) throw new NameTakenException();		
		for(String name : listIClients.keySet()) {
			listIClients.get(name).notifyEnter(username);
		}
		listIClients.put(username, client);
		System.out.println(username + " signed on");
	}

	@Override
	public synchronized List<String> getClientNames() throws RemoteException {
		List<String> connectedUsers = new ArrayList<String>();
		for(String name : listIClients.keySet())
			connectedUsers.add(name);
		return connectedUsers;
	}

	@Override
	public synchronized IClient getClient(String loginClient) throws UserNotConnectedException, RemoteException {
		if(!listIClients.containsKey(loginClient)) throw new UserNotConnectedException();
		return listIClients.get(loginClient);
	}

	@Override
	public synchronized void logOff(String leavingUser) throws RemoteException, UserNotConnectedException {
		if(!listIClients.containsKey(leavingUser)) throw new UserNotConnectedException();
		listIClients.remove(leavingUser);		
		// Notify to all client
		for(IClient client : listIClients.values()) {
			client.notifyLeave(leavingUser);
		}
		System.out.println(leavingUser + " log off");
	}



	@Override
	public void sendMessage(String sender, String message)
			throws RemoteException {
		for(String client : listIClients.keySet()) {
			if(!client.equals(sender)) {
				listIClients.get(client).sendPrivateMessage(sender, message);
			}
		}
	}

	
}
